<!--
 * @Author: XY
 * @Date: 2023-11-10 16:59:58
 * @LastEditors: XY
 * @LastEditTime: 2023-12-12 17:55:18
 * @FilePath: \friendsApp\see_you\src\views\settingPage\inform.vue
 -->
<template>
  <div class="inform" :style="{ 'margin-top': stickyHeight + 'px' }">
    <div class="inform-title">举报类型*</div>
    <div class="inform-radio">
      <van-radio-group v-model="params.rela_type">
        <van-radio v-for="item in listJson" :key="item.value" :name="item.value">{{ item.title }}</van-radio>
      </van-radio-group>
    </div>
    <div class="inform-title">举报理由</div>
    <div class="inform-text">
      <textarea :value="params.content" @change="setInputValue($event.target.value)" cols="30" rows="10"
        placeholder="请输入举报理由"></textarea>
    </div>
    <div class="inform-title">第三方平台举证截图</div>
    <div class="inform-upload">
      <van-uploader v-model="fileList" :before-read="beforeRead" :after-read="afterRead" max-count="3" />
    </div>

    <div class="inform-radio">
      <van-checkbox v-model="params.is_blacklist">拉黑此账号</van-checkbox>
    </div>
    <div class="inform-submit">
      <div class="inform-submit-btn" @click="submit">提交</div>
    </div>
  </div>
</template>

<script>
import { uploadImg, setServiceReport } from '@/api/setting.js'
import { Toast } from 'vant'
import * as imageConversion from 'image-conversion'
export default {
  name: 'HelloWorld',
  props: {
    showViewPop: {
      type: Boolean,
      default: false,
    },
    msg: String,
  },
  data() {
    return {
      stickyHeight: 0,

      listJson: [
        {
          title: '头像或个人资料造假',
          key: 'rela_type',
          value: 'avatar_profile',
        },
        {
          title: '骚扰、诽谤、辱骂等',
          key: 'rela_type',
          value: 'hara_abusive',
        },
        {
          title: '涉及低俗或色情等内容',
          key: 'rela_type',
          value: 'vulgar_content',
        },
        {
          title: '欺诈（酒托骗钱红包）',
          key: 'rela_type',
          value: 'fraud',
        },
        {
          title: '垃圾广告或拉人头',
          key: 'rela_type',
          value: 'advertisement',
        },
        {
          title: '违法行为（涉毒、暴恐、违禁品等）',
          key: 'rela_type',
          value: 'illegal',
        },
        {
          title: '涉及未成年人',
          key: 'rela_type',
          value: 'minor',
        },
        {
          title: '其他',
          key: 'rela_type',
          value: 'other',
        },
      ],
      fileList: [],
      params: {
        rela_type: null,
        report_uid: null,
        content: '',
        images: [],
        is_blacklist: false, //1是0 否
      },
    }
  },
  mounted() {
    this.stickyHeight = document.getElementById('navbar').clientHeight
    this.params.report_uid = this.$route.query.id
  },
  methods: {
    //校验图片的格式
    beforeRead(file) {
      let This = this
      // Array.isArray 是用来校验你是单张图片还是数组的形象做校验
      // 这是多张图片上传
      if (Array.isArray(file)) {
        file.forEach(item => {
          if (!item.type.startsWith('image')) {
            This.$toast("请上传图片！")
            return false
          } else if (item.size > 10485760) {
            This.$toast("图片超过10M！")
            return false
          }
        })
      } else {
      // 这是单张图片校验
        if (!file.type.startsWith('image')) {
          This.$toast("请上传图片！")
          return false
        }
        if (file.size > 10485760) {
          This.$toast("图片超过10M！")
          return false
        }
      }
      // 上传之前校验
      return new Promise((resolve, reject) => {
        // console.log('压缩前', file) // 压缩到400KB,大于400KB的图片都会进行压缩，小于则不会
        // 500是控制压缩大小的 根据你自己的需要调整 数值越小压缩越小
        imageConversion.compressAccurately(file, 500).then(res => {
          res = new File([res], file.name, { type: res.type, lastModified: Date.now() })
          // console.log('压缩后', res)
          resolve(res)
        })
      })
    },

    afterRead(file) {
      file.status = 'uploading'
      file.message = '上传中...'
      let maxW = 1024;
    let maxH = 1024;
    let size  = 1024 * 1024 * 3
    console.log(size,file.file.size)
      let canvas = document.createElement('canvas') // 创建Canvas对象(画布)
      let context = canvas.getContext('2d')

      let img = new Image()
      img.src = file.content // 指定图.片的DataURL(图片的base64编码数据)
      img.onload = () => {
        let radio; // 压缩比例
       
          if (file.file.size > size) {
            // 获得压缩宽高过后的大小（保证等比例缩放）
            radio = img.naturalWidth / maxW
            maxH = img.naturalHeight / radio
            canvas.height = maxH;
            canvas.width = maxW;
        context.clearRect(0, 0, maxW, maxH)
        context.drawImage(img, 0, 0, maxW, maxH)
        file.content = canvas.toDataURL(file.file.type, 0.8) // 0.92为默认压缩质量
        }
     
       
        file.status = 'success'
        file.message = '上传成功'
      }
    },
    setInputValue(e) {
      this.params.content = e
    },
    dataURLtoBlob(dataurl) {
      var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new Blob([u8arr], { type: mime })
    },
    uploadFun() {
      Toast.loading({
        message: '加载中...',
        forbidClick: true,
      })
      return new Promise((resolve, reject) => {
        this.fileList.map((val) => {
          let formData = new FormData()
          let file = new File(
            [this.dataURLtoBlob(val.content)],
            'dynamic.png',
            {
              type: 'image/jpeg',
            }
          )
          formData.append('file', file)
          formData.append('type', 'report') //上传类型
          uploadImg(formData).then((res) => {
            if (res.status == 200) {
              Toast.loading({
                message: '上传中...',
                forbidClick: true,
              })
              this.params.images = this.params.images.concat(res.data.url)
              if (this.params.images.length === this.fileList.length) {
                resolve()
              }
            }
          })
        })
      })
    },
    submit() {
      if (this.params.content == '') {
        Toast('请输入举报理由')
        return
      }
      if (this.params.rela_type == '') {
        Toast('请选择举报类型')
        return
      }
      if (this.fileList.length == 0) {
        Toast('请上传一张举证截图')
        return
      }
      if (this.params.is_blacklist == true) {
        this.params.is_blacklist = 1
      } else {
        this.params.is_blacklist = 0
      }
      this.uploadFun()
        .then((r) => {
          setServiceReport(this.params).then((res) => {
            Toast('提交成功')
            this.$router.go(-1)
          })
        })
        .catch((re) => {
          console.log(re)
        })
    },
  },
}
</script>

<style scoped lang="scss">
.inform {
  position: relative;
  padding: 15px;
  margin-bottom: 80px;

  &-title {
    font-size: 16px;
    font-weight: 500;
    color: #1a1a1a;
    line-height: 16px;
    padding-bottom: 15px;
  }

  &-radio {
    .van-radio-group>div {
      margin-bottom: 10px;
    }
  }

  &-text {
    height: 80px;
    background: #f5f5f5;
    border-radius: 8px;
    padding: 15px;
    font-size: 14px;
    margin-bottom: 24px;

    textarea {
      width: 100%;
      height: 100%;
      background: #f5f5f5;
      border-radius: 8px;
      border: none;
    }
  }

  &-upload {
    margin-bottom: 13px;
  }

  &-submit {
    position: fixed;
    width: 100%;
    bottom: 0;
    left: 0;
    right: 0;
    background: #fff;

    &-btn {
      height: 50px;
      background: linear-gradient(180deg, #3764ec 0%, #6b85f7 100%);
      border-radius: 8px;
      font-size: 16px;
      font-weight: 500;
      color: #ffffff;
      display: flex;
      justify-content: center;
      align-items: center;
      margin: 10px 30px 20px;
    }
  }
}
</style>
